import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken,getUserId} from '@/utils/auth' // get token from cookie
import applicationUserManager from '@/auth/applicationusermanager';
import { GetMenus } from '@/api/accessmanage';

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const allowList = ['login', 'callback','401'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  NProgress.start() // start progress bar
  const token = getToken();
  if (token) {
      next()
  } else {
    if (allowList.includes(to.name)) {
      next()
    } else {
      applicationUserManager.login();
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

async function initMenuFn(){
  const userId = getUserId();
  let menuItems = sessionStorage.getItem('menuitems')
  if (!menuItems) {
    let routerMenus = await GetMenus({ employeeId: userId });
     store.dispatch('menu/addMenu',routerMenus.data);
  }else{
      store.dispatch('menu/addMenu',JSON.parse(menuItems));
  }
  router.addRoutes(store.getters.menuitems);
  store.getters.menuitems.forEach((item,index) => {
    router.options.routes[index+5] = item;
  });
}